package com.red.service.impl;

import com.red.mapper.UserMapper;
import com.red.entity.User;
import com.red.service.UserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServiceImpl extends Service implements UserService {
    private UserMapper mapper;

    public UserServiceImpl() {
        mapper = session.getMapper(UserMapper.class);
    }

    public boolean add(User user) {
        boolean result = false;
        if (mapper.selectByA(user.getuAccount()) == null) {
            if (mapper.addUser(user.getuName(), user.getuAccount(), user.getuPassword(), user.getuEmail(), user.getuLevel()) > 0) {
                result = true;
            }
        }
        destroy();
        return result;
    }

    public User selectByAC(String account, String password) {
        HashMap<String, String> param = new HashMap<>();
        param.put("account", account);
        param.put("password", password);
        User user = mapper.selectByAC(param);
        destroy();
        return user;
    }

    /**
     * 查询所有用户
     *
     * @return json
     */
    public User[] selectAllUser(int page, int len, ArrayList<Integer> types) {
        Map<String, Object> pattern = new HashMap<>();
        int offset = (page - 1) * len;
        pattern.put("list", types);
        pattern.put("offset", offset);
        pattern.put("len", len);
        if (types.isEmpty()) {
            return null;
        }
        User[] users = mapper.selectAllUser(pattern);
        destroy();
        return users;
    }

    public User selectByHouse(int house_id) {
        User user = mapper.selectUserByHouse(house_id);
        destroy();
        return user;
    }

    public int getPages(List<Integer> types) {
        if (types.isEmpty())
            return 0;
        int pages = mapper.selectPages(types);
        session.close();
        return pages;
    }

    public int delete(ArrayList<Integer> seq) {
        if (seq.isEmpty()) return 0;
        int count = mapper.deleteUsers(seq);
        destroy();
        return count;
    }

    public int update(User user) {
        int count = mapper.updateUser(user);
        destroy();
        return count;
    }
}
